package com.onerway.api.impl;

import com.onerway.api.OnerWayClient;
import com.onerway.config.OnerWayConfig;
import com.onerway.entity.OnerWayResponse;
import com.onerway.entity.payment.PaymentRes;
import com.onerway.entity.payment.TxnOrder;
import com.onerway.entity.payment.UpdateOrder;
import com.onerway.exception.OnerWaySignException;
import com.onerway.util.SignUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 校验响应报文版本
 *
 * @author: ash
 */
@Slf4j
public class OnerWaySignClientImpl extends OnerWayClientDecorator {


    public OnerWaySignClientImpl(OnerWayConfig onerWayConfig, OnerWayClient onerWayClient) {
        super(onerWayConfig, onerWayClient);
    }

    public OnerWayResponse<PaymentRes> payment(TxnOrder txnOrder) throws IOException {
        OnerWayResponse<PaymentRes> paymentResOnerWayResponse = super.payment(txnOrder);

        if (TransactionHelper.isSuccess(paymentResOnerWayResponse)) {
            if (!SignUtil.verifySign(paymentResOnerWayResponse.getData().toTreeMap(), onerWayConfig.getSecret(), paymentResOnerWayResponse.getData().getSign())) {
                log.error("响应报文验签失败:{}", paymentResOnerWayResponse);

                throw new OnerWaySignException("响应报文验签失败");
            }
        } else {
            log.info("payment验签通过");
        }

        return paymentResOnerWayResponse;
    }


    @Override
    public OnerWayResponse<PaymentRes> updatePayment(UpdateOrder updateOrder) throws IOException {
        OnerWayResponse<PaymentRes> paymentResOnerWayResponse = super.updatePayment(updateOrder);
        if (TransactionHelper.isSuccess(paymentResOnerWayResponse)) {
            if (!SignUtil.verifySign(paymentResOnerWayResponse.getData().toTreeMap(), onerWayConfig.getSecret(), paymentResOnerWayResponse.getData().getSign())) {
                log.error("响应报文验签失败1{}", paymentResOnerWayResponse);

                throw new OnerWaySignException("响应报文验签失败");
            }

        } else {
            log.info("updatePayment验签通过");
        }
        return paymentResOnerWayResponse;
    }
}
